<?
require_once("../config/dbconn.php");require_once("../config/powercls.php");

if($act=='add'){
	$msg='';
	if(trim($flname)=='') $msg="请输入分类名\\n";
	if ($msg!=''){
		echo "<script>alert('$msg');history.back();</script>";exit();
	}
	
	//获取下列参数
	$orders=1;$depth=1;$path='';
	if ($fid==0){
		$sqlm="select id,orders,depth,path from {$db_prefix}newfl where 1 order by orders desc limit 1";
		$rsm=$db->get_one($sqlm);
		if ($rsm['id']){
			$orders=$rsm['orders']+1;
			$depth=1;
			$path='';
		}else{
			$orders=1;
			$depth=1;
			$path='';
		}
		
	}else{
		$sqlm="select id,orders,depth,path from {$db_prefix}newfl where id='$fid'";
		$rsm=$db->get_one($sqlm);
		$depth=$rsm['depth']+1;
		if ($rsm['path']) $path=$rsm['path'].",".$rsm['id'];else $path=$rsm['id'];
		//获取这个分类同级别的上一个
		$sqlm1="select id,orders,depth,path from {$db_prefix}newfl where fid='$fid' order by orders desc limit 1";
		$rsm1=$db->get_one($sqlm1);
		if ($rsm1['id']){
			$mid1=$rsm1['id'];
			//获取他的下级最大的orders
			$sqlxj="select * from {$db_prefix}newfl where find_in_set('$mid1',path)>0 order by orders desc limit 1";
			$rsxj=$db->get_one($sqlxj);
			if ($rsxj['id']){
				$orders=$rsxj['orders']+1;
			}else{
				$orders=$rsm1['orders']+1;
			}
		}else{
			$orders=$rsm['orders']+1;
		}
		
		
	}
	
	//插入数据库
		$sqlcr="insert into {$db_prefix}newfl(flname,fid,path,depth,addtime,orders) values('$flname','$fid','$path','$depth','$curtime','$orders')";
		$db->query($sqlcr);
		$CRID=$db->insert_id();
		//更新orders
		$sqlgx="update {$db_prefix}newfl set orders=orders+1 where id!='$CRID' and orders>='$orders'";
		$db->query($sqlgx);
		
		echo "<script>alert('分类添加成功');location.href='category.php';</script>";exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="?act=add">
  <table width="100%" border="0">
    <tr>
      <td>上一级</td>
      <td><label>
        <select name="fid">
		<option value="0">顶级分类</option>
		<?
		$sql="select * from {$db_prefix}newfl where 1 order by orders asc";
		$result=$db->query($sql);
		while($rs=$db->fetch_array($result)){
			echo "<option value='".$rs['id']."'";
			if ($fid==$rs['id']) echo " selected";
			echo ">".str_repeat("------",$rs['depth']-1).$rs['flname']."</option>";
		}
		$db->free_result($result);
		?>
        </select>
      </label></td>
    </tr>
    <tr>
      <td>分类</td>
      <td><label>
        <input type="text" name="flname" />
      </label></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="提交" /></td>
    </tr>
  </table>
</form>
</body>
</html>
